<?php

namespace App\Repository;

use App\Entity\AdminUser;
use App\Entity\AdminUserGroup;
use App\Entity\Notice;
use App\Entity\NoticeType;
use App\Utils\Base\FilterBase;
use App\Utils\Enum\NoticeEnum;
use App\Utils\Filter\Admin\System\NoticeFilter;
use App\Utils\Traits\FilterTrait;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\AbstractQuery;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method Notice|null find($id, $lockMode = null, $lockVersion = null)
 * @method Notice|null findOneBy(array $criteria, array $orderBy = null)
 * @method Notice[]    findAll()
 * @method Notice[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class NoticeRepository extends ServiceEntityRepository {
    use FilterTrait;

    public function __construct (ManagerRegistry $registry) {
        parent::__construct($registry, Notice::class);
    }

    /**
     * 查询
     * @param array $params
     * @return array|int|string
     */
    public function search ($params = [], $select = []) {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $query_builder = $this->filter(new NoticeFilter($params))
            ->andWhere(FilterBase::ALIAS.'.status = 1')
            ->setFirstResult(($page - 1) * $limit)
            ->setMaxResults($limit)
            ->orderBy(FilterBase::ALIAS.'.id', 'DESC');
        if ($select) {
            $query_builder->select(implode(',', $select));
        }
        return $query_builder->getQuery()->getArrayResult();
    }

    /**
     * 获取查询count
     * @param array $params
     * @return int|mixed|string
     */
    public function searchTotal ($params = []) {
        return $this->filter(new NoticeFilter($params))
            ->select('count('.FilterBase::ALIAS.'.id) as total')
            ->andWhere(FilterBase::ALIAS.'.status = 1')
            ->getQuery()
            ->getSingleScalarResult();
    }

    /**
     * 以数组形式返回数据
     * @param $id
     * @return int|mixed|string|null
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findToArray ($id) {
        return $this->createQueryBuilder('n')
            ->where('n.id = :id')
            ->setParameter('id', $id)
            ->getQuery()
            ->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY);
    }

    /**
     * 赋值关联数据
     * @param $notice
     */
    public function buildData (&$notice) {
        $notice_types = $this->getEntityManager()->getRepository(NoticeType::class)->findAllToArrayOne();
        $notice['notice_type_text'] = isset($notice['notice_type_id']) ? ($notice_types[$notice['notice_type_id']] ?? '-') : '-';
        $notice['created_at'] = isset($notice['created_at']) ? $notice['created_at']->format('Y-m-d H:i:s') : '-';
        // 发送方
        if (isset($notice['from_type'])) {
            switch ($notice['from_type']) {
                case NoticeEnum::FROM_TYPE_SYSTEM:
                    $notice['from_type_text'] = '系统';
                    $notice['from_id_text'] = '系统';
                    break;
                case NoticeEnum::FROM_TYPE_USER:
                    $notice['from_type_text'] = '用户';
                    $notice['from_id_text'] = '-';
                    $admin_user = $this->getEntityManager()->getRepository(AdminUser::class)->find($notice['from_id']);
                    if ($admin_user) {
                        $notice['from_id_text'] = $admin_user->getUsername();
                    }
                    break;
                default:
                    $notice['from_type_text'] = '-';
                    $notice['from_id_text'] = '-';
            }
        }
        // 接收方
        if (isset($notice['to_type'])) {
            switch ($notice['to_type']) {
                case NoticeEnum::TO_TYPE_ALL:
                    $notice['to_type_text'] = '全部';
                    $notice['to_id_text'] = '全部';
                    break;
                case NoticeEnum::TO_TYPE_USER_GROUP:
                    $notice['to_type_text'] = '用户组';
                    $notice['to_id_text'] = '-';
                    $admin_user_groups = $this->getEntityManager()->getRepository(AdminUserGroup::class)->findBy(['id' => $notice['to_id']]);
                    $admin_user_group_text = [];
                    foreach ($admin_user_groups as $admin_user_group) {
                        array_push($admin_user_group_text, $admin_user_group->getName());
                    }
                    $notice['to_id_text'] = implode('、', $admin_user_group_text);
                    break;
                case NoticeEnum::TO_TYPE_USER:
                    $notice['to_type_text'] = '用户';
                    $notice['to_id_text'] = '-';
                    $admin_users = $this->getEntityManager()->getRepository(AdminUser::class)->findBy(['id' => $notice['to_id']]);
                    $admin_user_text = [];
                    foreach ($admin_users as $admin_user) {
                        array_push($admin_user_text, $admin_user->getUsername());
                    }
                    $notice['to_id_text'] = implode('、', $admin_user_text);
                    break;
                default:
                    $notice['to_type_text'] = '-';
                    $notice['to_id_text'] = '-';
            }
        }
    }
}
